package com.spark.common.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spark.common.annotation.Dict;
import com.spark.common.constants.CacheConstants;
import com.spark.common.constants.Constants;
import com.spark.common.core.Result;
import com.spark.common.core.api.SparkCommonApi;
import com.spark.common.core.entity.model.DictModel;
import com.spark.common.utils.ReflectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * AOP切面处理：拦截带有 @DictTranslate 的方法，处理返回值。
 *
 * @author LYCHEE
 * @date 2025/3/25 15:52
 */
@Slf4j
@Aspect
@Component
public class DictTranslateAspect {

    @Lazy
    @Resource
    private SparkCommonApi sparkCommonApi;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    public RedisTemplate redisTemplate;

    @Around("@annotation(com.spark.common.annotation.DictTranslate)")
    public Object translateDict(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行目标方法获取返回值
        Object result = joinPoint.proceed();
        if (result instanceof Result) {
            Object data = ((Result) result).getResult();
            List<JSONObject> items = new ArrayList<>();
            //step.1 筛选出加了 Dict 注解的字段列表
            List<Field> dictFieldList = new ArrayList<>();
            // 字典数据列表， key = 字典code，value=数据列表
            Map<String, List<String>> dataListMap = new HashMap<>(5);
            if (data instanceof IPage) {
                log.debug("IPAGE_TRANSLATORS...");
                List<Object> records = ((IPage) data).getRecords();
                Boolean hasDict = checkHasDict(records);
                if (!hasDict) {
                    return result;
                }
                // 处理集合数据
                this.dealRecords(records, items, dictFieldList, dataListMap);
                // step.2 调用翻译方法，一次性翻译
                Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
                // step.3 将翻译结果填充到返回结果里
                this.setResult(items, dictFieldList, translText);
                ((IPage) ((Result) result).getResult()).setRecords(items);
                return result;
            } else if (data instanceof Collection) {
                log.debug("Collection_TRANSLATORS...");
                List<Object> records = (List<Object>) data;
                Boolean hasDict = checkHasDict(records);
                if (!hasDict) {
                    return result;
                }
                // 处理集合数据
                this.dealRecords(records, items, dictFieldList, dataListMap);
                // step.2 调用翻译方法，一次性翻译
                Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
                // step.3 将翻译结果填充到返回结果里
                this.setResult(items, dictFieldList, translText);
                ((Result) result).setResult(items);
                return result;
            } else {
                log.debug("OBJECT_TRANSLATORS...");
                List<Object> records = new ArrayList<>();
                records.add(data);
                Boolean hasDict = checkHasDict(records);
                if (!hasDict) {
                    return result;
                }
                // 处理集合数据
                this.dealRecords(records, items, dictFieldList, dataListMap);
                // step.2 调用翻译方法，一次性翻译
                Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
                // step.3 将翻译结果填充到返回结果里
                this.setResult(items, dictFieldList, translText);
                ((Result) result).setResult(items.get(0));
                return result;
            }
        }
        return result;
    }

    /**
     * 处理集合数据
     * @param records 记录
     * @param items 数据
     * @param dictFieldList 筛选出加了 Dict 注解的字段列表
     * @param dataListMap 字典数据列表， key = 字典code，value=数据列表
     */
    private void dealRecords (List<Object> records, List<JSONObject> items, List<Field> dictFieldList
            , Map<String, List<String>> dataListMap) {
        for (Object record : records) {
            String json = "{}";
            try {
                json = objectMapper.writeValueAsString(record);
            } catch (Exception e) {
                log.error("json解析失败{}", e.getMessage(), e);
            }
            JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
            // 遍历所有字段，把字典Code取出来，放到 map 里
            for (Field field : ReflectUtils.getAllFields(record)) {
                String value = item.getString(field.getName());
                if (StringUtils.isEmpty(value)) {
                    continue;
                }
                if (field.getAnnotation(Dict.class) != null) {
                    if (!dictFieldList.contains(field)) {
                        dictFieldList.add(field);
                    }
                    String code = field.getAnnotation(Dict.class).dictCode();
                    String text = field.getAnnotation(Dict.class).dictText();
                    String table = field.getAnnotation(Dict.class).dictTable();

                    List<String> dataList;
                    String dictCode = code;
                    if (!StringUtils.isEmpty(table)) {
                        dictCode = String.format("%s,%s,%s", table, text, code);
                    }
                    dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
                    this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
                }
            }
            items.add(item);
        }
    }

    /**
     * 将翻译结果填充到返回结果里
     * @param items 数据
     * @param dictFieldList 筛选出加了 Dict 注解的字段列表
     * @param translText 翻译数据
     */
    private void setResult(List<JSONObject> items, List<Field> dictFieldList, Map<String, List<DictModel>> translText) {
        for (JSONObject record : items) {
            for (Field field : dictFieldList) {
                String code = field.getAnnotation(Dict.class).dictCode();
                String text = field.getAnnotation(Dict.class).dictText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String fieldDictCode = code;
                if (!StringUtils.isEmpty(table)) {
                    fieldDictCode = String.format("%s,%s,%s", table, text, code);
                }
                String value = record.getString(field.getName());
                if (StringUtils.isNotEmpty(value)) {
                    List<DictModel> dictModels = translText.get(fieldDictCode);
                    if(CollectionUtils.isEmpty(dictModels)){
                        continue;
                    }
                    String textValue = this.translDictText(dictModels, value);
                    log.debug(" 字典Val : " + textValue);
                    log.debug(" __翻译字典字段__ " + field.getName() + Constants.DICT_TEXT_SUFFIX + "： " + textValue);
                    record.put(field.getName() + Constants.DICT_TEXT_SUFFIX, textValue);
                }
            }
        }
    }

    /**
     * 一次性把所有的字典都翻译了
     * 1.  所有的普通数据字典的所有数据只执行一次SQL
     * 2.  表字典相同的所有数据只执行一次SQL
     * @param dataListMap
     * @return
     */
    private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) {
        // 翻译后的字典文本，key=dictCode
        Map<String, List<DictModel>> translText = new HashMap<>(5);
        // 需要翻译的数据（有些可以从redis缓存中获取，就不走数据库查询）
        List<String> needTranslData = new ArrayList<>();
        //step.1 先通过redis中获取缓存字典数据
        for (String dictCode : dataListMap.keySet()) {
            List<String> dataList = dataListMap.get(dictCode);
            if (CollectionUtils.isEmpty(dataList)) {
                continue;
            }
            // 表字典需要翻译的数据
            List<String> needTranslDataTable = new ArrayList<>();
            for (String s : dataList) {
                String data = s.trim();
                if (StringUtils.isEmpty(data)) {
                    continue;
                }
                if (dictCode.contains(",")) {
                    String keyString = String.format(CacheConstants.DICT_TABLE_TRANSLATORS.concat("::SimpleKey [%s,%s]"), dictCode, data);
                    if (Boolean.TRUE.equals(redisTemplate.hasKey(keyString))) {
                        try {
                            String text = Objects.requireNonNull(redisTemplate.opsForValue().get(keyString)).toString();
                            List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                            list.add(new DictModel(data, text));
                        } catch (Exception e) {
                            log.warn(e.getMessage());
                        }
                    } else if (!needTranslDataTable.contains(data)) {
                        // 去重添加
                        needTranslDataTable.add(data);
                    }
                } else {
                    String keyString = String.format(CacheConstants.DICT_TRANSLATORS.concat("::%s:%s"), dictCode, data);
                    if (Boolean.TRUE.equals(redisTemplate.hasKey(keyString))) {
                        try {
                            String text = Objects.requireNonNull(redisTemplate.opsForValue().get(keyString)).toString();
                            List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                            list.add(new DictModel(data, text));
                        } catch (Exception e) {
                            log.warn(e.getMessage());
                        }
                    } else if (!needTranslData.contains(data)) {
                        // 去重添加
                        needTranslData.add(data);
                    }
                }
            }
            // step.2 调用数据库翻译表字典
            if (!needTranslDataTable.isEmpty()) {
                String[] arr = dictCode.split(",");
                String table = arr[0], text = arr[1], code = arr[2];
                String values = String.join(",", needTranslDataTable);
                List<DictModel> texts = sparkCommonApi.translateDictFromTableByKeys(table, text, code, values);
                List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                list.addAll(texts);
                // 做 redis 缓存
                for (DictModel dict : texts) {
                    String redisKey = String.format(CacheConstants.DICT_TABLE_TRANSLATORS.concat("::SimpleKey [%s,%s]"), dictCode, dict.getValue());
                    try {
                        // 保留5分钟
                        redisTemplate.opsForValue().set(redisKey, dict.getText(), 300, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.warn(e.getMessage(), e);
                    }
                }
            }
        }
        //step.3 调用数据库进行翻译普通字典
        if (!needTranslData.isEmpty()) {
            List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{}));
            // 将不包含逗号的字典code筛选出来，因为带逗号的是表字典，而不是普通的数据字典
            List<String> filterDictCodes = dictCodeList.stream().filter(key -> !key.contains(",")).collect(Collectors.toList());
            String dictCodes = String.join(",", filterDictCodes);
            String values = String.join(",", needTranslData);
            Map<String, List<DictModel>> manyDict = sparkCommonApi.translateManyDict(dictCodes, values);
            for (String dictCode : manyDict.keySet()) {
                List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                List<DictModel> newList = manyDict.get(dictCode);
                list.addAll(newList);

                // 做 redis 缓存
                for (DictModel dict : newList) {
                    String redisKey = String.format(CacheConstants.DICT_TRANSLATORS.concat("::%s:%s"), dictCode, dict.getValue());
                    try {
                        redisTemplate.opsForValue().set(redisKey, dict.getText());
                    } catch (Exception e) {
                        log.warn(e.getMessage(), e);
                    }
                }
            }
        }
        return translText;
    }


    /**
     * 字典值替换文本
     *
     * @param dictModels
     * @param values
     * @return
     */
    private String translDictText(List<DictModel> dictModels, String values) {
        List<String> result = new ArrayList<>();

        // 允许多个逗号分隔，允许传数组对象
        String[] splitVal = values.split(",");
        for (String val : splitVal) {
            String dictText = val;
            for (DictModel dict : dictModels) {
                if (val.equals(dict.getValue())) {
                    dictText = dict.getText();
                    break;
                }
            }
            result.add(dictText);
        }
        return String.join(",", result);
    }

    /**
     * list 去重添加
     */
    private void listAddAllDeduplicate(List<String> dataList, List<String> addList) {
        // 筛选出dataList中没有的数据
        List<String> filterList = addList.stream().filter(i -> !dataList.contains(i)).collect(Collectors.toList());
        dataList.addAll(filterList);
    }

    /**
     * 检测返回结果集中是否包含Dict注解
     *
     * @param records 记录
     * @return 是否
     */
    private Boolean checkHasDict(List<Object> records) {
        if (!CollectionUtils.isEmpty(records)) {
            Field[] fields = ReflectUtils.getAllFields(records.get(0));
            for (Field field : fields) {
                if (Objects.nonNull(field.getAnnotation(Dict.class))) {
                    return true;
                }
            }
        }
        return false;
    }


}
